const express = require("express");
const router = express.Router();
const path = require("path");
const utils = require("../utils/index.js");
const moment = require("moment-timezone");
const multer = require("multer");
const AdmZip = require("adm-zip");
const AppInfoParser = require("app-info-parser");
const plist = require("plist");
const fs = require("fs");
const msgUtils = require("../utils/feishu.js");
const crypto = require("crypto");
const CryptoJS = require("crypto-js");
const FormData = require("form-data");
const {
    exec
} = require("child_process");
const config = require("../config");
const axios = require("axios");
const jwt = require("jsonwebtoken");
const pool = require("../pool.js");
// const SunoApi = require('./sunoApi.js'); // 路径依你实际放置调整



// Suno 模拟浏览器请求类
class SunoBrowserAPI {
    constructor(config) {
        this.authorization = config.authorization; // Bearer token
        this.deviceId = config.deviceId;
        this.cookies = config.cookies;
        this.sessionId = config.sessionId;
        this.clientToken = config.clientToken;
        this.browserToken = config.browserToken;

        // 设置默认的请求头，完全模拟浏览器
        this.defaultHeaders = {
            'accept': '*/*',
            'accept-language': 'zh-CN,zh;q=0.9',
            'sec-ch-ua': '"Not)A;Brand";v="99", "Google Chrome";v="127", "Chromium";v="127"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-site',
            'Referer': 'https://suno.com/',
            'Referrer-Policy': 'strict-origin-when-cross-origin',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36',
            'cookie': this.cookies
        };

        // 创建axios实例，禁用SSL验证以避免证书问题
        this.httpClient = axios.create({
            timeout: 30000,
            headers: this.defaultHeaders,
            validateStatus: function (status) {
                return status < 500; // 不要在4xx错误时抛出异常
            }
        });
    }

    // 更新浏览器token时间戳
    updateBrowserToken() {
        const timestamp = Date.now();
        this.browserToken = `{"token":"eyJ0aW1lc3RhbXAiOjE3NTc5MDEyMjA5MDV9"}`;
        return this.browserToken;
    }
    // 会话保活 - 完全按照你的请求格式
    async touchSession() {
        try {
            const url = `https://clerk.suno.com/v1/client?__clerk_api_version=2025-04-10&_clerk_js_version=5.93.0`;

            const response = await this.httpClient.post(url, {
                headers: {
                    'content-type': 'application/x-www-form-urlencoded',
                    'priority': 'u=1, i',
                    'cookie': `singular_device_id=778bb43e-2300-48b5-b5b8-9e73878f51a3; _gcl_au=1.1.886223204.1757486707; _ga=GA1.1.1110031952.1757486708; _axwrt=a83b1e03-e6aa-40da-a1a7-06f4c0c6216d; _fbp=fb.1.1757486712475.168790000562151607; _tt_enable_cookie=1; _ttp=01K4S5Y2E05ESPRF2QA061ZC59_.tt.1; afUserId=0ecddb89-5d2a-4e80-aa68-3ec4a65d3be3-p; AF_SYNC=1757486760465; __stripe_mid=9fc3ecc9-4a0f-4227-842a-57c9d19a81f8fa4d6f; ajs_anonymous_id=9ee60a33-5d33-4dad-8c7c-ea315c4985c3; cf_clearance=MdqSpxBVkbjYFBF7ugdzk1OK4yeO.95yBeA7w8RnLHw-1757486853-1.2.1.1-kazvFUw_jw5zZE3nK44b6qRU8KiCOJ3ndZFtqfsDAlsydnEFZ2CkRoo571lKw8xUvknf8SIJXfSNJ4uv7MdU.UxILAsy_rDn5WQqEyX2AW_QIJdDEUF2.8j0Ep5ByalKE8xGUu9HA6mOFjkFabr5UjOUWe9vaCeG6ndrN2knxGA2yVDVqBUiPWws4GuzQYU7lMqgvdvadIuT6XuInGXrb33UGbk1bNQJYkeE5dJRrz4; __client=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6ImNsaWVudF8zMlVzdGdJb0djME83dnozM05JV2tqeDh6Q00iLCJyb3RhdGluZ190b2tlbiI6InFvbmV4dHA1N2VxdWV3NGNiZGc4dXdmOW5udWw4c2tuaWsyNmtscXoifQ.asCe4rZr2V5vtZd9WhQE9r6KEM-NKUDQ4h2o4ideIMRDxm7JFSxTDaYSo6FqoyhiylySeGQjCibSsLhEjVNhFjT8wihyiVfxoBYiV0ptdP6zFWlqhy9LvqChGEEFE-HnM40DPlSvQgU8aAuMiSOsqv5KDPR29Cmq0fWP2Oj5xc9r_yNUWl9bCsjLg_LOTZK5cjrBCxqht7ocWgtWB9KRpqW3TrHOBBGl96uLzkP5VBgtdQ711nzyV35Qhu9IV0g3tvpMPT3bYdyhBxaZtEaE6JHFzdShIOBvlvEUuN6rPana2HposHGlTMfH6R2Q0Dcd0V4EikVCLI81vGfzWV-rRQ; __client_uat=1757909281; __client_uat_U9tcbTPE=1757909281; _cfuvid=mrNHW41UglxZwgyue3sUsm0x5UkGD3oCsUBoZLlaRdY-1757913678137-0.0.1.1-604800000; __stripe_sid=ba098b86-5f2a-4356-916e-7a1652b203dd06a992; __cf_bm=A7ETOJyB9dudall3CRm8ua1A4i_YNF.6l7d9fCDSnfA-1757914889-1.0.1.1-3CFj0DAnmfm_DHRnW53p9gcBjqhqCK11noCEn2jLaSDsSOi9dpllT.oRarjbAnLruyESnV_AFvYncZxf_uTcMXQlQhHuArJvzPX83DV_2QE; _uetsid=982b2ca091d511f085817347387985ec|1esy8x8|2|fzc|0|2084; ttcsid=1757914370533::q19lm0PgZYKYG6598rif.6.1757914895017; ttcsid_CT67HURC77UB52N3JFBG=1757914370532::XGoDeLsnb-jOm3mF6SFK.6.1757914895253; _uetvid=b39538408e1111f0a0f8fbc3986dc6d6|1em6aky|1757914895822|4|1|bat.bing.com/p/conversions/c/n; ax_visitor=%7B%22firstVisitTs%22%3A1757486771027%2C%22lastVisitTs%22%3A1757905006181%2C%22currentVisitStartTs%22%3A1757914272536%2C%22ts%22%3A1757915155648%2C%22visitCount%22%3A5%7D; _ga_7B0KEDD7XP=GS2.1.s1757914274$o6$g1$t1757915156$j60$l0$h0`
                }
            });

            console.log('Session touch response status:', response.status);
            console.log('Session touch response data:', response.data);

            return {
                success: response.status === 200,
                status: response.status,
                data: response.data,
                message: response.status === 200 ? 'Session touched successfully' : 'Session touch failed'
            };
        } catch (error) {
            console.error('Session touch error:', error.message);
            return {
                success: false,
                error: error.message,
                status: error.response?.status || 0
            };
        }
    }

    // 生成音乐 - 完全按照你的请求格式
    async generateMusic(params) {
        try {
            // 更新浏览器token
            this.updateBrowserToken();

            const requestBody = {
                token: params.token,
                gpt_description_prompt: params.description || "生万物",
                mv: params.model || "chirp-v3-5",
                prompt: params.customPrompt || "",
                metadata: {
                    create_mode: params.createMode || "simple",
                    user_tier: params.userTier || "4497580c-f4eb-4f86-9f0e-960eb7c48d7d",
                    lyrics_model: params.lyricsModel || "default",
                    can_control_sliders: params.canControlSliders || []
                },
                make_instrumental: params.makeInstrumental || false,
                user_uploaded_images_b64: params.userUploadedImages || [],
                generation_type: params.generationType || "TEXT"
            };

            console.log('Generating music with params:', JSON.stringify(requestBody, null, 2));

            const response = await this.httpClient.post(
                'https://studio-api.prod.suno.com/api/generate/v2-web/',
                JSON.stringify(requestBody),
                {
                    headers: {
                        'authorization': `Bearer ${this.authorization}`,
                        'browser-token': this.browserToken,
                        'content-type': 'text/plain;charset=UTF-8',
                        'device-id': this.deviceId,
                        'affiliate-id': 'undefined',
                        'priority': 'u=1, i',
                        'cookie': this.cookies
                    }
                }
            );

            console.log('Music generation response status:', response.status);
            console.log('Music generation response data:', JSON.stringify(response.data, null, 2));

            if (response.status === 200) {
                const taskIds = this.extractClipIds(response.data);
                return {
                    success: true,
                    data: response.data,
                    taskIds: taskIds,
                    message: 'Music generation started successfully'
                };
            } else {
                return {
                    success: false,
                    status: response.status,
                    error: 'Generation failed',
                    data: response.data
                };
            }
        } catch (error) {
            console.error('Music generation error:', error.message);
            return {
                success: false,
                error: error.message,
                status: error.response?.status || 0,
                data: error.response?.data || null
            };
        }
    }

    // 从生成响应中提取任务ID
    extractClipIds(responseData) {
        const clipIds = [];
        try {
            if (responseData && Array.isArray(responseData.clips)) {
                responseData.clips.forEach(clip => {
                    if (clip && clip.id) {
                        clipIds.push(clip.id);
                    }
                });
            }
        } catch (error) {
            console.error('Error extracting clip IDs:', error.message);
        }
        return clipIds;
    }

    // 查询生成结果 - 完全按照你的请求格式
    async checkGenerationStatus(taskIds) {
        try {
            // 更新浏览器token
            this.updateBrowserToken();

            const idsString = Array.isArray(taskIds) ? taskIds.join('%2C') : taskIds;
            const url = `https://studio-api.prod.suno.com/api/feed/v2?ids=${idsString}`;

            console.log('Checking status for URL:', url);

            const response = await this.httpClient.get(url, {
                headers: {
                    'authorization': `Bearer ${this.authorization}`,
                    'browser-token': this.browserToken,
                    'device-id': this.deviceId,
                    'affiliate-id': 'undefined',
                    'priority': 'u=1, i',
                    'cookie': this.cookies
                }
            });

            console.log('Status check response status:', response.status);
            console.log('Status check response data:', JSON.stringify(response.data, null, 2));

            return {
                success: response.status === 200,
                data: response.data,
                status: response.status,
                message: response.status === 200 ? 'Status checked successfully' : 'Status check failed'
            };
        } catch (error) {
            console.error('Status check error:', error.message);
            return {
                success: false,
                error: error.message,
                status: error.response?.status || 0,
                data: error.response?.data || null
            };
        }
    }

    // 轮询等待生成完成
    async waitForCompletion(taskIds, maxAttempts = 30, intervalMs = 5000) {
        console.log(`开始轮询任务状态, 任务ID: ${taskIds}, 最大尝试次数: ${maxAttempts}`);

        let attempts = 0;

        while (attempts < maxAttempts) {
            attempts++;
            console.log(`第 ${attempts}/${maxAttempts} 次轮询...`);

            const result = await this.checkGenerationStatus(taskIds);
            if (!result.success) {
                console.log('状态检查失败:', result.error);
                await new Promise(resolve => setTimeout(resolve, intervalMs));
                continue;
            }

            const songs = result.data;

            // 新增判断：所有audio_url就绪马上返回
            const allAudioReady = Array.isArray(songs) && songs.length > 0 &&
                songs.every(song => song.audio_url && song.audio_url !== "");

            if (allAudioReady) {
                console.log('所有歌曲的 audio_url 都已就绪!');
                return {
                    success: true,
                    data: songs,
                    completed: true,
                    message: `所有音频已生成 (${songs.length} 首)`
                };
            }

            // 等待下一次轮询
            console.log(`等待 ${intervalMs / 1000} 秒后继续检查...`);
            await new Promise(resolve => setTimeout(resolve, intervalMs));
        }

        console.log('轮询超时, 获取最终状态...');
        const finalResult = await this.checkGenerationStatus(taskIds);

        return {
            success: false,
            error: 'Generation timeout',
            data: finalResult.success ? finalResult.data : null,
            timeout: true,
            attempts: attempts,
            message: `轮询超时 (${attempts} 次尝试)`
        };
    }
}

// 配置管理

const currentConfig = {
    authorization: 'eyJhbGciOiJSUzI1NiIsImNhdCI6ImNsX0I3ZDRQRDExMUFBQSIsImtpZCI6Imluc18yT1o2eU1EZzhscWRKRWloMXJvemY4T3ptZG4iLCJ0eXAiOiJKV1QifQ.eyJhdWQiOiJzdW5vLWFwaSIsImF6cCI6Imh0dHBzOi8vc3Vuby5jb20iLCJleHAiOjE3NTc5MTc5NjEsImZ2YSI6Wzg1LC0xXSwiaHR0cHM6Ly9zdW5vLmFpL2NsYWltcy9jbGVya19pZCI6InVzZXJfMzJpaFFDMFp3UGlReHVxVmpoVmJpWlJkcFhGIiwiaHR0cHM6Ly9zdW5vLmFpL2NsYWltcy9lbWFpbCI6ImxpdWRhb3l1YW4wMDhAMTYzLmNvbSIsImh0dHBzOi8vc3Vuby5haS9jbGFpbXMvcGhvbmUiOm51bGwsImlhdCI6MTc1NzkxNDM2MSwiaXNzIjoiaHR0cHM6Ly9jbGVyay5zdW5vLmNvbSIsImp0aSI6IjllZTJjZWZiNWY0ZmZmMmViOTExIiwibmJmIjoxNzU3OTE0MzUxLCJzaWQiOiJzZXNzXzMyaWhRQklock9wckRSYzFNT2JrOTJ1WUdRTSIsInN0cyI6ImFjdGl2ZSIsInN1YiI6InVzZXJfMzJpaFFDMFp3UGlReHVxVmpoVmJpWlJkcFhGIn0.Fia3D2NG2-ey-Ih78zALI1XGVpNtvF6lPYEzRI-um-S9ZfhXRGF-p6RAk3rtmzzM-0Qirt40ruqd2XzmSBGKFfN5_7vW9vCVWNUVjVh2ggcKDmKqaCZkaE3xFoQE_rvqXzjV9vMYQl8rhgxZGXSH_q8-1mCKsrq2A6RZZ9vJEp00CkieHfdi0kAgacehEtbRm9RvcTWExcpZC9PpSzpZG2ofPZAYNkv8p0EJPcFDBkgyI1vIl6sYyyYnkqzrItTfgHIYqfdLx1VJlTH_Fr3jDp15BgrXnnwbfbo2anglNdpK-Vc0JC2yk2diDU9XbiG_Df1J9--HlUXa3Zgts0SUwA',
    deviceId: '1',
    sessionId: '1',
    browserToken: '1',
    cookies: 'singular_device_id=778bb43e-2300-48b5-b5b8-9e73878f51a3; _gcl_au=1.1.886223204.1757486707; _ga=GA1.1.1110031952.1757486708; _axwrt=a83b1e03-e6aa-40da-a1a7-06f4c0c6216d; _fbp=fb.1.1757486712475.168790000562151607; _tt_enable_cookie=1; _ttp=01K4S5Y2E05ESPRF2QA061ZC59_.tt.1; afUserId=0ecddb89-5d2a-4e80-aa68-3ec4a65d3be3-p; AF_SYNC=1757486760465; __stripe_mid=9fc3ecc9-4a0f-4227-842a-57c9d19a81f8fa4d6f; ajs_anonymous_id=9ee60a33-5d33-4dad-8c7c-ea315c4985c3; cf_clearance=MdqSpxBVkbjYFBF7ugdzk1OK4yeO.95yBeA7w8RnLHw-1757486853-1.2.1.1-kazvFUw_jw5zZE3nK44b6qRU8KiCOJ3ndZFtqfsDAlsydnEFZ2CkRoo571lKw8xUvknf8SIJXfSNJ4uv7MdU.UxILAsy_rDn5WQqEyX2AW_QIJdDEUF2.8j0Ep5ByalKE8xGUu9HA6mOFjkFabr5UjOUWe9vaCeG6ndrN2knxGA2yVDVqBUiPWws4GuzQYU7lMqgvdvadIuT6XuInGXrb33UGbk1bNQJYkeE5dJRrz4; __client=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6ImNsaWVudF8zMlVzdGdJb0djME83dnozM05JV2tqeDh6Q00iLCJyb3RhdGluZ190b2tlbiI6InFvbmV4dHA1N2VxdWV3NGNiZGc4dXdmOW5udWw4c2tuaWsyNmtscXoifQ.asCe4rZr2V5vtZd9WhQE9r6KEM-NKUDQ4h2o4ideIMRDxm7JFSxTDaYSo6FqoyhiylySeGQjCibSsLhEjVNhFjT8wihyiVfxoBYiV0ptdP6zFWlqhy9LvqChGEEFE-HnM40DPlSvQgU8aAuMiSOsqv5KDPR29Cmq0fWP2Oj5xc9r_yNUWl9bCsjLg_LOTZK5cjrBCxqht7ocWgtWB9KRpqW3TrHOBBGl96uLzkP5VBgtdQ711nzyV35Qhu9IV0g3tvpMPT3bYdyhBxaZtEaE6JHFzdShIOBvlvEUuN6rPana2HposHGlTMfH6R2Q0Dcd0V4EikVCLI81vGfzWV-rRQ; __client_uat=1757909281; __client_uat_U9tcbTPE=1757909281; _cfuvid=mrNHW41UglxZwgyue3sUsm0x5UkGD3oCsUBoZLlaRdY-1757913678137-0.0.1.1-604800000; __stripe_sid=ba098b86-5f2a-4356-916e-7a1652b203dd06a992; __cf_bm=A7ETOJyB9dudall3CRm8ua1A4i_YNF.6l7d9fCDSnfA-1757914889-1.0.1.1-3CFj0DAnmfm_DHRnW53p9gcBjqhqCK11noCEn2jLaSDsSOi9dpllT.oRarjbAnLruyESnV_AFvYncZxf_uTcMXQlQhHuArJvzPX83DV_2QE; _uetsid=982b2ca091d511f085817347387985ec|1esy8x8|2|fzc|0|2084; ttcsid=1757914370533::q19lm0PgZYKYG6598rif.6.1757914895017; ttcsid_CT67HURC77UB52N3JFBG=1757914370532::XGoDeLsnb-jOm3mF6SFK.6.1757914895253; _uetvid=b39538408e1111f0a0f8fbc3986dc6d6|1em6aky|1757914895822|4|1|bat.bing.com/p/conversions/c/n; ax_visitor=%7B%22firstVisitTs%22%3A1757486771027%2C%22lastVisitTs%22%3A1757905006181%2C%22currentVisitStartTs%22%3A1757914272536%2C%22ts%22%3A1757915155648%2C%22visitCount%22%3A5%7D; _ga_7B0KEDD7XP=GS2.1.s1757914274$o6$g1$t1757915156$j60$l0$h0'
};

// API路由

// 健康检查
router.get('/health', (req, res) => {
    res.json({
        status: 'OK',
        timestamp: new Date().toISOString(),
        config: {
            hasAuth: !!currentConfig.authorization,
            hasCookies: !!currentConfig.cookies,
            sessionId: currentConfig.sessionId
        }
    });
});

// 更新配置
router.post('/api/suno/config', (req, res) => {
    try {
        const { authorization, deviceId, sessionId, browserToken, cookies } = req.body;

        if (authorization) currentConfig.authorization = authorization;
        if (deviceId) currentConfig.deviceId = deviceId;
        if (sessionId) currentConfig.sessionId = sessionId;
        if (browserToken) currentConfig.browserToken = browserToken;
        if (cookies) currentConfig.cookies = cookies;

        console.log('配置已更新:', {
            hasAuth: !!currentConfig.authorization,
            hasCookies: !!currentConfig.cookies,
            deviceId: currentConfig.deviceId,
            sessionId: currentConfig.sessionId
        });

        res.json({
            success: true,
            message: 'Configuration updated successfully',
            config: {
                hasAuth: !!currentConfig.authorization,
                hasCookies: !!currentConfig.cookies,
                deviceId: currentConfig.deviceId,
                sessionId: currentConfig.sessionId
            }
        });
    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
});

// 会话保活
router.post('/api/suno/session/touch', async (req, res) => {
    try {
        if (!currentConfig.authorization || !currentConfig.cookies) {
            return res.status(400).json({
                success: false,
                error: 'Missing authorization or cookies. Please update config first.'
            });
        }

        const sunoAPI = new SunoBrowserAPI(currentConfig);
        const result = await sunoAPI.touchSession();
        res.json(result);
    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
});

// 生成音乐
// router.post('/api/suno/generate', async (req, res) => {
//     try {
//         if (!currentConfig.authorization || !currentConfig.cookies) {
//             return res.status(400).json({
//                 success: false,
//                 error: 'Missing authorization or cookies. Please update config first.'
//             });
//         }

//         const {
//             token,
//             description,
//             model,
//             customPrompt,
//             createMode,
//             userTier,
//             lyricsModel,
//             makeInstrumental,
//             generationType,
//             canControlSliders,
//             userUploadedImages
//         } = req.body;

//         if (!token) {
//             return res.status(400).json({
//                 success: false,
//                 error: 'Token is required'
//             });
//         }

//         const params = {
//             token,
//             description,
//             model,
//             customPrompt,
//             createMode,
//             userTier,
//             lyricsModel,
//             makeInstrumental,
//             generationType,
//             canControlSliders,
//             userUploadedImages
//         };

//         const sunoAPI = new SunoBrowserAPI(currentConfig);

//         // 先尝试保活会话
//         console.log('尝试保活会话...');
//         const touchResult = await sunoAPI.touchSession();
//         console.log('会话保活结果:', touchResult);

//         // 生成音乐
//         console.log('开始生成音乐...');
//         const result = await sunoAPI.generateMusic(params);
//         res.json(result);

//     } catch (error) {
//         console.error('生成音乐时出错:', error);
//         res.status(500).json({ success: false, error: error.message });
//     }
// });

// 查询生成状态
router.get('/api/suno/status/:taskIds', async (req, res) => {
    try {
        if (!currentConfig.authorization || !currentConfig.cookies) {
            return res.status(400).json({
                success: false,
                error: 'Missing authorization or cookies. Please update config first.'
            });
        }

        const { taskIds } = req.params;
        const idsArray = taskIds.split(',');

        const sunoAPI = new SunoBrowserAPI(currentConfig);
        const result = await sunoAPI.checkGenerationStatus(idsArray);
        res.json(result);

    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
});

// 完整的生成并等待完成
router.post('/api/suno/generate-and-wait', async (req, res) => {
    try {
        if (!currentConfig.authorization || !currentConfig.cookies) {
            return res.status(400).json({
                success: false,
                error: 'Missing authorization or cookies. Please update config first.'
            });
        }

        const {
            token,
            description,
            model,
            customPrompt,
            createMode,
            userTier,
            lyricsModel,
            makeInstrumental,
            generationType,
            canControlSliders,
            userUploadedImages,
            maxAttempts,
            intervalMs
        } = req.body;

        if (!token) {
            return res.status(400).json({
                success: false,
                error: 'Token is required'
            });
        }

        const params = {
            token,
            description,
            model,
            customPrompt,
            createMode,
            userTier,
            lyricsModel,
            makeInstrumental,
            generationType,
            canControlSliders,
            userUploadedImages
        };

        const sunoAPI = new SunoBrowserAPI(currentConfig);

        // 保活会话
        console.log('保活会话...');
        const touchResult = await sunoAPI.touchSession();

        // 生成音乐
        console.log('生成音乐...');
        const generateResult = await sunoAPI.generateMusic(params);
        if (!generateResult.success) {
            return res.json(generateResult);
        }
        // 等待生成完成
        console.log('等待生成完成...');
        const waitResult = await sunoAPI.waitForCompletion(
            generateResult.taskIds.join(','),
            maxAttempts || 30,
            intervalMs || 5000
        );

        res.json({
            touchResult,
            generateResult,
            waitResult,
            success: waitResult.success,
            message: waitResult.message
        });

    } catch (error) {
        console.error('完整生成流程出错:', error);
        res.status(500).json({ success: false, error: error.message });
    }
});


/**
 * 生成音乐 API
 * POST /api/suno/generate
 * 入参：
 * {
 *   prompt: string,
 *   makeInstrumental: boolean,
 *   model: string,
 *   waitAudio: boolean
 * }
 * Cookie可以放 header/cookie 字段，也可直接写死
 */
router.post('/api/suno/generate', async (req, res) => {
    console.log('进')
    try {
        const { prompt, makeInstrumental, model, waitAudio } = req.body;
        // 推荐：从header/cookie字段取用户cookie
        // const cookies = req.headers.cookie || process.env.SUNO_COOKIE;
        const cookies = `singular_device_id=778bb43e-2300-48b5-b5b8-9e73878f51a3; _gcl_au=1.1.886223204.1757486707; _ga=GA1.1.1110031952.1757486708; _axwrt=a83b1e03-e6aa-40da-a1a7-06f4c0c6216d; _fbp=fb.1.1757486712475.168790000562151607; _tt_enable_cookie=1; _ttp=01K4S5Y2E05ESPRF2QA061ZC59_.tt.1; afUserId=0ecddb89-5d2a-4e80-aa68-3ec4a65d3be3-p; AF_SYNC=1757486760465; __stripe_mid=9fc3ecc9-4a0f-4227-842a-57c9d19a81f8fa4d6f; ajs_anonymous_id=9ee60a33-5d33-4dad-8c7c-ea315c4985c3; cf_clearance=MdqSpxBVkbjYFBF7ugdzk1OK4yeO.95yBeA7w8RnLHw-1757486853-1.2.1.1-kazvFUw_jw5zZE3nK44b6qRU8KiCOJ3ndZFtqfsDAlsydnEFZ2CkRoo571lKw8xUvknf8SIJXfSNJ4uv7MdU.UxILAsy_rDn5WQqEyX2AW_QIJdDEUF2.8j0Ep5ByalKE8xGUu9HA6mOFjkFabr5UjOUWe9vaCeG6ndrN2knxGA2yVDVqBUiPWws4GuzQYU7lMqgvdvadIuT6XuInGXrb33UGbk1bNQJYkeE5dJRrz4; _cfuvid=RbXE3ln4TJ9q0Za9dGc0DCRyO5zaTMMZaPKx0DpJby4-1757921942049-0.0.1.1-604800000; __stripe_sid=360a53c9-dd6b-4a8b-8b8f-7f78c914cf65183fae; __client=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6ImNsaWVudF8zMlVzdGdJb0djME83dnozM05JV2tqeDh6Q00iLCJyb3RhdGluZ190b2tlbiI6Im42emV3OWVzaWxiMjI0c2pwZHJhM2RkYnRuZDRubGI3cGc5Z2U3bTEifQ.uMgnEP-RdzRaY3K7X4o79D0VSS37RMHys3XUHzBVXT7c0hhpqBHOPkM0jITZ_d5NpCK9vE8mk9soA9JguYruvTWn4Il1QGSbp9FuwLtcb1K7BksQs8JRSPw6Lhf6ObMQ69WYjT8M94g59XqmLPCKWfSnGupRQRwkSLRYMubK8EcdTLr83ZfYPfkqNojaJWyjBeuUDn0VhN6RR0ykQ_ab6Fmq92XTOwD4IogtygDogRPVyA1PWxY6s2f3-oLmkWc22sE1GjG9KDsPqPHTp49FBXCpnjRpEob7HXpVsmTt6zw2S9maLzgpIMtGTedHhaMDlEGh_uSomWlBjWypvgdEQg; __client_uat=1757929551; __client_uat_U9tcbTPE=1757929551; __cf_bm=AkyUq5e9HlqBjH6QFu9YfiNTmt9IqDQWqF4Xub5qVEQ-1757929551-1.0.1.1-EFozyN34Xc6JD5Dnu0szLvqB_5vqP.mfGR9cS_96I9kMBamz8BtarDp9J5vgWXjvE6pYXSi3SVHAwEMptZPYl6ClkJtZIhIzUiuCIBkoHNXbCxjl4C4fDJjjgdMyNPxz; _ga_7B0KEDD7XP=GS2.1.s1757927388$o8$g1$t1757929609$j11$l0$h0; _uetsid=982b2ca091d511f085817347387985ec|1esy8x8|2|fzc|0|2084; ttcsid=1757927460826::JQNBpAkXlmJBVut3WNUK.8.1757929610890; ttcsid_CT67HURC77UB52N3JFBG=1757927460826::4rdAFWI3eSEYzExgWiuV.8.1757929611130; _uetvid=b39538408e1111f0a0f8fbc3986dc6d6|1s4oy4a|1757929613074|10|1|bat.bing.com/p/conversions/c/n; ax_visitor=%7B%22firstVisitTs%22%3A1757486771027%2C%22lastVisitTs%22%3A1757914272536%2C%22currentVisitStartTs%22%3A1757927386114%2C%22ts%22%3A1757929879794%2C%22visitCount%22%3A6%7D`;
        if (!cookies) return res.status(401).json({ success: false, error: '缺少用户cookie' });

        // 新建实例、初始化
        const suno = await new SunoApi(cookies).init();
        // 生成歌曲（保活/验证码全部自动）
        const result = await suno.generate(prompt, makeInstrumental, model, waitAudio);
        res.json({ success: true, data: result });
    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
});
 
/**
 * 查询音乐状态 API
 * GET /api/suno/status/:ids
 * ids: 逗号分隔ID字符串
 */
router.get('/api/suno/status/:ids', async (req, res) => {
    try {
        const ids = req.params.ids.split(',');
        const cookies = req.headers.cookie || process.env.SUNO_COOKIE;
        if (!cookies) return res.status(401).json({ success: false, error: '缺少用户cookie' });

        const suno = await new SunoApi(cookies).init();
        const result = await suno.get(ids);
        res.json({ success: true, data: result });
    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
});


async function mysqlQuery(sql, arr) {
    return new Promise((resolve, reject) => {
        pool.query(sql, arr, (error, results, fields) => {
            if (error) {
                return reject(error);
            }
            resolve(results);
        });
    });
}
// 加密函数
function encrypt(message, key, iv) {
    const keyHex = CryptoJS.enc.Utf8.parse(key);
    const ivHex = CryptoJS.enc.Utf8.parse(iv);
    // 加密模式为CBC，填充模式为PKCS7
    const encrypted = CryptoJS.DES.encrypt(message, keyHex, {
        iv: ivHex,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7,
    });
    return encrypted.toString();
}

// 解密函数
function decrypt(ciphertext, key, iv) {
    const keyHex = CryptoJS.enc.Utf8.parse(key);
    const ivHex = CryptoJS.enc.Utf8.parse(iv); // 使用key的前8个字符作为IV
    // 解密模式为CBC，填充模式为PKCS7
    const decrypted = CryptoJS.DES.decrypt(
        {
            ciphertext: CryptoJS.enc.Base64.parse(ciphertext),
        },
        keyHex,
        {
            iv: ivHex,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7,
        }
    );
    return decrypted.toString(CryptoJS.enc.Utf8);
}
module.exports = router;